from helpers import updateInfo
import re
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class AddComment(webapp.RequestHandler):
    """ Add comments to competitions AJAX class """

    def post(self):
        self.response.headers['Content-Type'] = 'application/json'
        try:
            if self.request.method == 'POST':
                data=self.request.POST.copy()
                commentkey=db.Key(data.get("commentkey"))
                userref=users.get_current_user()
                usernick=userref.nickname().capitalize()
                commenttext=data.get("commenttext")
                # Strip HTML tags (still simple)
                commenttext=re.sub(r'<[^>]*?>', '', commenttext)
                comment = updateInfo.Comment(commentkey=commentkey, userref=userref, usernick=usernick, commenttext=commenttext)
                comment.put()
                self.response.out.write(simplejson.dumps({'status': 'success', 'commenttext' : commenttext, 'usernick': usernick}))
            else:
                self.response.out.write(simplejson.dumps({'status': 'error'}))
            
        except:
            self.response.out.write(simplejson.dumps({'status': 'error'}))

application = webapp.WSGIApplication(
                                     [('/ajax/comments', AddComment)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
